package com.gitee.sop.adminserver.api.system;

import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.annotation.Api;
import com.gitee.easyopen.annotation.ApiService;
import com.gitee.easyopen.doc.annotation.ApiDoc;
import com.gitee.easyopen.doc.annotation.ApiDocMethod;
import com.gitee.easyopen.session.SessionManager;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.sop.adminserver.api.system.param.LoginForm;
import com.gitee.sop.adminserver.api.system.result.AdminUserInfoVO;
import com.gitee.sop.adminserver.common.AdminErrors;
import com.gitee.sop.adminserver.common.WebContext;
import com.gitee.sop.adminserver.entity.AdminUserInfo;
import com.gitee.sop.adminserver.freeway.api.ums.UmUserService;
import com.gitee.sop.adminserver.freeway.bean.ums.UserResult;
import com.gitee.sop.adminserver.mapper.AdminUserInfoMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author tanghc
 */
@ApiService
@ApiDoc("系统接口")
public class SystemApi {


    public static final int STATUS_FORBIDDEN = 2;
    @Autowired
    AdminUserInfoMapper adminUserInfoMapper;

    @Autowired
    private UmUserService umUserService;


    private final static String HCP_KEY = "HCP";

    @Api(name = "nologin.admin.login")
    @ApiDocMethod(description = "用户登录")
    String adminLogin(LoginForm param) {
        String username = param.getUsername();
        String password = param.getPassword();
        password = DigestUtils.md5Hex(username + password + username);

        Query query = new Query()
                .eq("username", username)
                .eq("password", password);
        AdminUserInfo user = adminUserInfoMapper.getByQuery(query);




        if (user == null) {
            throw AdminErrors.ERROR_USERNAME_PWD.getException();
        } else {
            if (user.getStatus() == STATUS_FORBIDDEN) {
                throw AdminErrors.USER_FORBIDDEN.getException();
            }
            SessionManager sessionManager = ApiContext.getSessionManager();
            // 生成一个新session
            HttpSession session = sessionManager.getSession(null);
            WebContext.getInstance().setLoginUser(session, user);
            return session.getId();
        }
    }
    @Api(name = "nologin.admin.ssologin")
    @ApiDocMethod(description = "用户SSO登录")
    String ssoLogin(){

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();

        WebContext.getInstance().setUmUserService(umUserService);

        String HCP = "";
        if(request.getHeader(HCP_KEY)!=null){
            HCP = request.getHeader(HCP_KEY);
        }else if(request.getCookies()!=null && request.getCookies().length>0){
            Optional<Cookie> cookie = Arrays.stream(request.getCookies()).filter(i->{
                if(i.getName().equals(HCP_KEY)){
                    return true;
                }
                return false;
            }).findFirst();
            if(cookie!=null && cookie.isPresent()){
                HCP = cookie.get().getValue();
            }
        }else{
            throw AdminErrors.NO_USER.getException();
        }

        if(!StringUtils.isEmpty(HCP)){
            UserResult userResult = umUserService.getByToken(HCP);
            if(userResult!=null){

                SessionManager sessionManager = ApiContext.getSessionManager();
                // 根据hcp生成session 其实就是cookie 和access_token（在前端）
                HttpSession session = sessionManager.getSession(HCP);
                WebContext.getInstance().setUMLoginUser(session,userResult);

                return session.getId();
            }else {

                throw AdminErrors.NO_USER.getException();
            }
        }

        throw AdminErrors.NO_USER.getException();
    }


    @Api(name = "admin.userinfo.get")
    @ApiDocMethod(description = "获取用户信息")
    AdminUserInfoVO getAdminUserInfo() {
        UserResult loginUser = WebContext.getInstance().getUMLoginUserUm();
        if(loginUser!=null) {
            AdminUserInfoVO adminUserInfoVO = new AdminUserInfoVO();
            BeanUtils.copyProperties(loginUser, adminUserInfoVO);
            return adminUserInfoVO;
        }
        return null;
    }
}
